package com.example.laserharp1;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class ConnectionPage extends AppCompatActivity {

    Button btnDiscover, back, home, function;
    ListView listView;
    TextView connectionStatus;

    WifiManager wifiManager;
    WifiP2pManager mManager;
    WifiP2pManager.Channel mChannel;

    BroadcastReceiver mReceiver;
    IntentFilter mIntentFilter;

    List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
    List<String> deviceNameArray = new ArrayList<>();
    WifiP2pDevice[] deviceArray;

    ServerClass serverClass;
    ClientClass clientClass;
    SendReceive sendReceive;

    ArrayAdapter<String> listAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connection_page);

        initialWork();          // 初始化
        exqListener();          // 按键功能
    }

    // 初始化
    private void initialWork() {
        btnDiscover = (Button) findViewById(R.id.discover);
        listView = (ListView) findViewById(R.id.peerListView);
        connectionStatus = (TextView) findViewById(R.id.connectionStatus);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);

        mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);

        back = findViewById(R.id.back);
        home = findViewById(R.id.home);
        function = findViewById(R.id.function);

        listAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, deviceNameArray);
        listView.setAdapter(listAdapter);

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            Toast.makeText(this, "请打开wifi", Toast.LENGTH_SHORT).show();
        }
    }

    private void exqListener() {
        btnDiscover.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                deviceNameArray.clear();
                listAdapter.notifyDataSetChanged();

                mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        connectionStatus.setText("connection status:  discovering");
                    }

                    @Override
                    public void onFailure(int reason) {
                        connectionStatus.setText("connction status:  discovery failed");
                    }
                });

                //扫描wifi信号
                scan();
            }
        });         // Discover按钮，若成功，connection status 显示 Discovery started。

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @SuppressLint("MissingPermission")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String ssid = deviceNameArray.get(i);
                showPwdDialog(ssid);

//                final WifiP2pDevice device = deviceArray[i];
//                WifiP2pConfig config = new WifiP2pConfig();
//                config.deviceAddress = device.deviceAddress;
//
//                mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
//                    @Override
//                    public void onSuccess() {
//                        Toast.makeText(getApplicationContext(), "connecting to " + device.deviceName, Toast.LENGTH_SHORT).show();
//                        GlobalVariable.device = device.deviceName;
//                    }
//
//                    @Override
//                    public void onFailure(int reason) {
//                        Toast.makeText(getApplicationContext(), "connection failed", Toast.LENGTH_SHORT).show();
//                    }
//                });
            }
        });         // 搜寻到其他设备后，点击设备名称，进行连接


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConnectionPage.this, MainActivity.class);
                startActivity(intent);
            }
        });

        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConnectionPage.this, MainActivity.class);
                startActivity(intent);
            }
        });

        function.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ConnectionPage.this, FunctionPage.class);
                startActivity(intent);
            }
        });
    }


    /****************以下为设备连接部分*****************/


    WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {          // 获取可连接的设备信息，以listview呈出在橘黄色区域
            if (!peerList.getDeviceList().equals(peers)) {
                peers.clear();
                peers.addAll(peerList.getDeviceList());

                deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
                int index = 0;

                for (WifiP2pDevice device : peerList.getDeviceList()) {
                    deviceNameArray.add(device.deviceName);
                    deviceArray[index] = device;
                    index++;
                }

                listAdapter.notifyDataSetChanged();
            }                   // 若搜不到设备，出现提示
            if (peers.size() == 0) {
                connectionStatus.setText("connection status: no device found");
                return;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }       // BroadcastReceiver相关

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }       // BroadcastReceiver相关


    /************** 以下为信息发送部分*****************/

    WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
            final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;

            if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner) {
                connectionStatus.setText("connection status:  success (client)");
                serverClass = new ServerClass();
                serverClass.start();
            }           // Host机为Server class
            else if (wifiP2pInfo.groupFormed) {
                connectionStatus.setText("connection status:  success (server)");
                clientClass = new ClientClass(groupOwnerAddress);
                clientClass.start();
            }           // Client机为Client class

        }
    };

    private void scan() {
        //操作WiFi的基础类,所有的WiFi操作都需要使用这个管理类
        final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        wifiManager.startScan();
        List<ScanResult> list = wifiManager.getScanResults();
        for (ScanResult scanResult : list) {
            Log.e("TAG", "wifi名称:" + scanResult.SSID
                    + "强度:" + scanResult.level +
                    "类型:" + scanResult.capabilities);
//            if (scanResult.SSID.equals("TP-LINK_1D4E")) { //找到我们需要的WiFi
//                connectionWifi(scanResult.SSID, "yuanxuehai", scanResult.capabilities); //连接它
//            }
            //过滤掉一样名称的WiFi
            if (!deviceNameArray.contains(scanResult.SSID)) {
                deviceNameArray.add(scanResult.SSID);
            }
        }
        listAdapter.notifyDataSetChanged();
    }

    /**
     * 连接WiFi的方法
     *
     * @param ssid         wifi名称
     * @param password     WiFi密码
     * @param capabilities 加密方式
     */
    private void connectionWifi(String ssid, String password, String capabilities) {
        Log.e("TAG", "触发connectionWifi");
        //操作WiFi的基础类,所有的WiFi操作都需要使用这个管理类
        final WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        ssid = "\"" + ssid + "\"";          //WiFi的名称配置需要加引号
        password = "\"" + password + "\"";  //WiFi的密码配置需要加引号
        wifiConfiguration.SSID = ssid;
        if (capabilities.contains("WPA")) {
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
            wifiConfiguration.preSharedKey = password;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

        } else if (capabilities.contains("WEP")) {
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.wepKeys[0] = password;
            wifiConfiguration.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        } else if (capabilities.contains("OPEN")) {
            wifiConfiguration.wepKeys[0] = "";
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        wifiManager.addNetwork(wifiConfiguration);
        @SuppressLint("MissingPermission") List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration item : wifiConfigurationList) {
            if (item.SSID == null) {
                continue;
            } else if (item.SSID.equals(ssid)) {
                Log.e("TAG", "item的SSID:" + item.SSID);
                wifiManager.enableNetwork(item.networkId, true); //连接我们需要的WiFi
                Log.e("TAG", "item的networkId:" + item.networkId);
                Log.e("TAG", "触发wifiManager.enableNetwork");
            }
        }
    }

    private void showPwdDialog(final String ssid) {
        final EditText et = new EditText(this);
        et.setHint("请输入wifi密码");
        new AlertDialog.Builder(this).setTitle(ssid)
                .setView(et)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String pwd = et.getText().toString();
                        if (TextUtils.isEmpty(pwd)) {
                            Toast.makeText(getApplicationContext(), "请输入wifi密码", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        connectionWifi(ssid, pwd, "WPA");
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**************** 以下代码只为获取ip地址   app界面上server获取client地址    若板子上相反，只需修改调换client和server***************/

    public class ServerClass extends Thread {
        Socket socket;
        ServerSocket serverSocket;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(8888);
                socket = serverSocket.accept();
                sendReceive = new SendReceive(socket);
                sendReceive.start();
            }                                       // 用来发送和接受
            catch (IOException e) {
                e.printStackTrace();
            }

        }
    }           // Server class：相当于host

    public class SendReceive extends Thread {
        private Socket socket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public SendReceive(Socket skt) {
            socket = skt;
            try {
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }   // 创建constructor： 获取input stream 和 output stream

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;

            while (socket != null) {
                try {
                    bytes = inputStream.read(buffer);
                    if (bytes > 0) {
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }                                       // run method： 调用handler，获取信息

    }           // 作为server和client之间的connection

    public class ClientClass extends Thread {
        Socket socket;
        String hostAdd;

        public ClientClass(InetAddress hostAddress) {
            hostAdd = hostAddress.getHostAddress();
            socket = new Socket();
            GlobalVariable.ip = hostAdd;
        }

        @Override
        public void run() {
            try {
                socket.connect(new InetSocketAddress(hostAdd, 8888), 500);  // 和host相同的port：8888
                sendReceive = new SendReceive(socket);
                sendReceive.start();
            }                                      // 调用SendReceive用来发送和接受host地址的信息
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }           // Client class： 相当于client
}